package com.imesne.office.excel.read;

import com.imesne.office.excel.model.ExcelCell;
import com.imesne.office.excel.model.ExcelRange;
import com.imesne.office.excel.utils.ExcelKitUtils;
import com.imesne.office.excel.validation.CellValueValidator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.List;

/**
 * Created by liyd on 17/7/3.
 */
public class ExcelCellReaderImpl extends AbstractConfigReader implements ExcelCellReader {

    public boolean isSupportRead(Workbook workbook, Sheet sheet, int sheetIndex, Row row, int rowIndex, Cell cell, int cellIndex) {
        List<ExcelRange> ranges = this.getExcelReaderConfig().getExcelRanges();
        //未指定，不限范围
        if (ranges == null || ranges.isEmpty()) {
            return true;
        }
        for (ExcelRange range : ranges) {
            if (range.getSheetNum() - 1 != sheetIndex) {
                continue;
            }
            if (rowIndex < range.getBeginRowNum() - 1 || rowIndex > range.getEndRowNum() - 1) {
                continue;
            }
            if (cellIndex >= range.getBeginCellNum() - 1 && cellIndex <= range.getEndCellNum() - 1) {
                return true;
            }
        }
        return false;
    }

    public ExcelCell readExcelCell(Workbook workbook, Sheet sheet, int sheetIndex, Row row, int rowIndex, Cell cell, int cellIndex) {

        ExcelCell excelCell = new ExcelCell();
        excelCell.setCellNum(cellIndex + 1);

        if (cell == null) {
            return excelCell;
        }
        excelCell.setCell(cell);
        String cellValue = ExcelKitUtils.getCellValue(cell);
        List<CellValueValidator> cellValueValidators = this.getExcelReaderConfig().getCellValueValidators();
        for (CellValueValidator cellValueValidator : cellValueValidators) {
            boolean supportValidate = cellValueValidator.isSupportValidate(workbook, sheet, sheetIndex, row, rowIndex, cellIndex);
            if (!supportValidate) {
                continue;
            }
            cellValueValidator.validate(cellValue, sheetIndex, rowIndex, cellIndex);
        }
        excelCell.setValue(cellValue);
        return excelCell;
    }
}
